package com.ygqh.baby.handler;

import com.ygqh.baby.ao.Message;
import com.ygqh.baby.model.PromotionTag;
import com.ygqh.baby.service.RedisCacheEvictService;
import com.ygqh.baby.service.YgProductService;
import com.ygqh.baby.solr.ProductSolrApi;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 〈〉
 *
 * @author guohao
 * @date 2019/3/8 12:11
 * @since 1.0.0
 */
public abstract class AbstractProductPromotionTagHandler implements IProductPromotionTagHandler {

    @Autowired
    private YgProductService ygProductService;
    @Autowired
    private RedisCacheEvictService redisCacheEvictService;
    @Autowired
    private ProductSolrApi productSolrApi;

    @Override
    public Message updatePromotionTag(Long relateId, List<Long> addList, List<Long> deleteList) {

        PromotionTag promotionTag = getPromotionTag(relateId);

        check(relateId, addList, deleteList, promotionTag.isExpired());

        doUpdate(addList, promotionTag.getTagName());
        doUpdate(deleteList, "");
        return Message.success(promotionTag);
    }

    private void doUpdate(List<Long> idList, String promotionTag) {
        if (CollectionUtils.isEmpty(idList)) {
            return;
        }
        ygProductService.updatePromotionTag(promotionTag, idList);
        productSolrApi.updateProductSolr(idList);
        redisCacheEvictService.evictProductByIds(idList.toArray(new Long[]{}));
    }

    protected abstract PromotionTag getPromotionTag(Long relateId);

    protected abstract void check(Long relateId, List<Long> addList, List<Long> deleteList, Boolean isExpired);
}
